﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using XnaColor = Microsoft.Xna.Framework.Color;

namespace GT.Xna.Windows
{
    public static partial class GameExtensions
    {
        #region Texture2D

        public static void Draw(this Texture2D texture)
        {
            texture.Draw(GameGlobals.DefaultSettings.StartPosition.To2D());
        }

        public static void Draw(this Texture2D texture, Vector2 location)
        {
            GameGlobals.DefaultSpriteBatch.Draw(texture, Vector2.Add(location, GameGlobals.Origin.To2D()), XnaColor.White);
        }

        public static void Draw(this Texture2D texture, int x, int y)
        {
            GameGlobals.DefaultSpriteBatch.Draw(texture, Vector2.Add(new Vector2(x, y), GameGlobals.Origin.To2D()), XnaColor.White);
        }

        public static byte[] GetBytes(this Texture2D texture)
        {
            byte[] ret = null;
            using (MemoryStream ms = new MemoryStream())
            {
                texture.GetImage().Save(ms, ImageFormat.Png);
                ret = ms.ToArray();
            }
            return ret;
        }

        public static Image GetImage(this Texture2D texture)
        {
            if (texture == null)
                return null;

            if (texture.IsDisposed)
                return null;

            Image ret = null;

            // Memory stream to store the bitmap data.
            using (MemoryStream ms = new MemoryStream())
            {
                // Save the texture to the stream. 
                texture.SaveAsPng(ms, texture.Width, texture.Height);

                // Seek the beginning of the stream.
                ms.Seek(0, SeekOrigin.Begin);

                // Create an image from a stream.
                ret = System.Drawing.Bitmap.FromStream(ms);
            }
            return ret;
        }

        #endregion
    }
}
